package exteditapp.state;

import exteditapp.AppletIterator;
import exteditapp.FileDefault;
import exteditapp.action.ActionIdlingLocked;
import exteditapp.command.CommandCheck;

/**
 * State - none (no file is loaded)
 * @author Arturas Smorgun, arturas@smorgun.lt
 */
public class StateIdlingLocked extends IState {

	String label1 = "FILE IS LOCKED BY ";
	String label2 = "LAST MODIFIED AT ";
	
	String modified;
	String lockAuthor;
	
	int checkPeriod;

	protected int lastExec = 0;
	
	/**
	 * Default constructor
	 * @param iterator is system iterator, which performs all actions
	 * @param file this is file, which state we will hold
	 */
	public StateIdlingLocked(AppletIterator iterator, FileDefault file) {
		super(iterator, file);
		start();
	}
	public StateIdlingLocked(AppletIterator iterator, FileDefault file, boolean doRegister){
		super(iterator, file, doRegister);
		start();
	}
	
	protected void start() {
		this.setAction(new ActionIdlingLocked());
		System.out.println("SUKURIAME MOD "+modified);
		checkPeriod = Integer.parseInt(file.getModule().getSettings().getParameter("fileCheckInterval"));
		file.getModule().getInvoker().execute(new CommandCheck(this.file));
		
		if(this.getLifetime() % 10 == 0){
			if(lockAuthor == null){
				lockAuthor = file.getModule().getSettings().getParameter("lockAuthor");
				if(lockAuthor.compareTo("") == 0)
					lockAuthor = "OTHER PARTY";
			}
			this.getAction().setText(label1 + lockAuthor + "#WAIT UNTIL UNLOCK");
		}
		else if((this.getLifetime() + 5) % 10 == 0){
			if(modified == null)
				modified = file.getModule().getSettings().getParameter("fileModified");
			this.getAction().setText(label2 + modified + "#EDIT IN EXTERNAL EDITOR");
		}
	}

	/**
	 * Handling of new state
	 */
	public boolean handle() {
		
		//TODO implement "none - updated" state handling
		//
		if(this.getLifetime() > 0 && this.getLifetime() % checkPeriod == 0 && lastExec != this.getLifetime()){
			file.getModule().getInvoker().execute(new CommandCheck(this.file));
			lastExec = this.getLifetime();
		}
		return false;
	}
	
}
